using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;

namespace NetduinoHappyHour.Hardware
{
    class Sharp2d120x : ISensor
    {
        private SecretLabs.NETMF.Hardware.AnalogInput _inputPort;
        // Microframework does not support multidimensional arrays
        private int[][] _distanceValues = new int[2][];

        /// <summary>
        /// Default Constructor, call Init required for proper use
        /// </summary>
        public Sharp2d120x()
        {
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="PinToRead"></param>
        public Sharp2d120x(Cpu.Pin PinToRead)
        {
            Init(PinToRead);
        }

        public void Init(Cpu.Pin PinToRead)
        {
            if (_inputPort == null)
            {
                _distanceValues[0] = new int[] { 740, 530, 400, 340, 300, 260, 230, 210, 190, 180, 175 };
                _distanceValues[1] = new int[] { 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24 };

                _inputPort = new SecretLabs.NETMF.Hardware.AnalogInput(PinToRead);
            }
        }

        public void Init(Cpu.Pin PinToRead, Cpu.Pin PinToTrigger)
        {
            throw new NotImplementedException();
        }

        public string GetSensorType()
        {
            return "range";
        }

        public string GetDescription()
        {
            return "Sharp 2d 120x triangulation range detector";
        }

        /// <summary>
        /// Returns distance measured in cm
        /// </summary>
        /// <param name="ticks"></param>
        /// <returns>Distance in cm, -1L if measurement was out of range</returns>
        public double GetDistance()
        {
            int actualValue = GetDigitalValue();
            
            for (int i = 0; i < _distanceValues[0].Length; i++)
            {
                if (_distanceValues[0][i] < actualValue)
                {
                    return _distanceValues[1][i];
                }
            }

            return -1L;
        }

        public int GetDigitalValue()
        {
            return _inputPort.Read();
        }

        public void Dispose()
        {
            _inputPort.Dispose();
        }
    }
}
